package com.prs.crm.dao.sale.impl;

import java.io.Serializable;
import java.util.Collection;
import java.util.List;

import org.hibernate.Criteria;
import org.hibernate.HibernateException;
import org.hibernate.Session;
import org.hibernate.criterion.Restrictions;
import org.springframework.orm.hibernate3.HibernateCallback;

import com.prs.crm.dao.impl.BaseDaoImpl;
import com.prs.crm.dao.sale.RetrunsDao;
import com.prs.crm.domain.sale.Returns;
import com.prs.crm.domain.sale.SalesContract;
import com.prs.crm.domain.sale.SalesContractDetail;
import com.prs.crm.domain.stock.Product;
import com.prs.crm.domain.stock.ProductStore;

public class ReturnsDaoImpl extends BaseDaoImpl<Returns> implements RetrunsDao {

	@SuppressWarnings("unchecked")
	@Override
	public SalesContractDetail getSalesContractDetail(
			final SalesContract salesContract, final Product product) {
		return (SalesContractDetail) getHibernateTemplate().execute(
				new HibernateCallback() {
					public Object doInHibernate(Session session)
							throws HibernateException {
						Criteria criteria = session
								.createCriteria(SalesContractDetail.class);
						criteria
								.add(
										Restrictions.eq("salesContract",
												salesContract)).add(
										Restrictions.eq("product", product));
						List<ProductStore> result = criteria.list();
						if (result.size() > 0)
							return result.get(0);
						else
							return null;
					}
				});
	}

	@Override
	public Returns getReturnObject(Serializable id) {
		// TODO Auto-generated method stub
		return this.getHibernateTemplate().get(Returns.class, id);
	}

	@Override
	public void saveOrUpdate(Returns re) {
		this.getHibernateTemplate().saveOrUpdate(re);

	}

	@SuppressWarnings("unchecked")
	@Override
	public Collection<Returns> getReturnsBysalesContract(
			SalesContract salesContract) {
		Criteria criteria = this.getSession().createCriteria(Returns.class);
		criteria.add(Restrictions.eq("salesContract", salesContract));
		return criteria.list();
	}

}
